<template>
  <div class="travel-posts">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="container">
        <div class="row align-items-center">
          <div class="col-md-6">
            <h1 class="page-title">精选游记</h1>
            <p class="page-subtitle">发现旅行者们的精彩故事与独特体验</p>
          </div>
          <div class="col-md-6 text-md-end">
            <el-button type="primary" size="large" @click="goToCreate">
              <el-icon><Edit /></el-icon>
              写游记
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 筛选和搜索 -->
    <div class="filter-section">
      <div class="container">
        <div class="filter-card">
          <div class="row align-items-center">
            <div class="col-lg-4 col-md-6 mb-3">
              <el-input
                v-model="filters.keyword"
                placeholder="搜索游记标题、内容..."
                @keyup.enter="handleSearch"
                @clear="handleSearch"
                clearable
              >
                <template #prepend>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>
            <div class="col-lg-2 col-md-3 col-sm-6 mb-3">
              <el-select v-model="filters.location" placeholder="目的地" @change="handleSearch" clearable>
                <el-option
                  v-for="location in locations"
                  :key="location"
                  :label="location"
                  :value="location"
                />
              </el-select>
            </div>
            <div class="col-lg-2 col-md-3 col-sm-6 mb-3">
              <el-select v-model="filters.sortBy" placeholder="排序方式" @change="handleSearch">
                <el-option label="最新发布" value="createTime" />
                <el-option label="最多浏览" value="viewCount" />
                <el-option label="最多点赞" value="likeCount" />
              </el-select>
            </div>
            <div class="col-lg-2 col-md-6 col-sm-6 mb-3">
              <el-select v-model="filters.tag" placeholder="标签" @change="handleSearch" clearable>
                <el-option
                  v-for="tag in tags"
                  :key="tag"
                  :label="tag"
                  :value="tag"
                />
              </el-select>
            </div>
            <div class="col-lg-2 col-md-6 col-sm-6 mb-3">
              <el-button type="primary" @click="handleSearch" style="width: 100%">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 游记列表 -->
    <div class="posts-section">
      <div class="container">
        <div v-if="loading" class="loading-container">
          <el-skeleton :rows="3" animated />
        </div>
        
        <div v-else-if="posts.length === 0" class="empty-container">
          <el-empty description="暂无游记数据">
            <el-button type="primary" @click="goToCreate">写第一篇游记</el-button>
          </el-empty>
        </div>
        
        <div v-else class="posts-grid">
          <div class="row">
            <div
              v-for="post in posts"
              :key="post._id"
              class="col-lg-4 col-md-6 col-sm-12 mb-4"
            >
              <div class="post-card" @click="goToPost(post._id)">
                <div class="post-image">
                  <img :src="post.cover" :alt="post.title" />
                  <div class="post-overlay">
                    <div class="post-stats">
                      <span><i class="bi bi-eye"></i> {{ formatNumber(post.viewCount) }}</span>
                      <span><i class="bi bi-heart"></i> {{ formatNumber(post.likeCount) }}</span>
                    </div>
                  </div>
                </div>
                <div class="post-content">
                  <div class="post-tags">
                    <el-tag
                      v-for="tag in post.tags.slice(0, 2)"
                      :key="tag"
                      size="small"
                      effect="plain"
                    >
                      {{ tag }}
                    </el-tag>
                  </div>
                  <h3 class="post-title">{{ post.title }}</h3>
                  <p class="post-location">
                    <i class="bi bi-geo-alt"></i>
                    {{ post.location }}
                  </p>
                  <div class="post-excerpt" v-html="truncateText(post.content, 120)"></div>
                  <div class="post-meta">
                    <div class="author-info">
                      <img :src="post.author.avatar || defaultAvatar" :alt="post.author.nickname" class="author-avatar" />
                      <div class="author-details">
                        <span class="author-name">{{ post.author.username }}</span>
                        <span class="post-date">{{ formatDate(post.createTime) }}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination-container" v-if="totalPages > 1">
          <el-pagination
            v-model:current-page="pagination.page"
            :page-size="pagination.pageSize"
            :total="pagination.total"
            :hide-on-single-page="false"
            layout="prev, pager, next, jumper, total"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { defaultAvatar } from '@/assets/images'
import { ElButton, ElInput, ElSelect, ElOption, ElIcon, ElTag, ElSkeleton, ElEmpty, ElPagination, ElMessage } from 'element-plus'
import { Search, Edit } from '@element-plus/icons-vue'
import { getHotPosts, searchPosts ,getNotes} from '@/api/data'
import type { TravelPost } from '@/types/http'

const router = useRouter()
const route = useRoute()

// 响应式数据
const loading = ref(false)
const posts = ref([])

// 筛选条件
const filters = reactive({
  keyword: '',
  location: '',
  sortBy: 'createTime',
  tag: ''
})

// 分页信息
const pagination = reactive({
  page: 1,
  pageSize: 12,
  total: 0
})

// 筛选选项
const locations = ref(['北京', '上海', '广州', '深圳', '成都', '西安', '杭州', '南京', '重庆', '天津', '云南', '西藏', '新疆', '三亚'])
const tags = ref(['自驾游', '亲子游', '情侣游', '摄影', '美食', '文化', '自然风光', '历史古迹', '海岛', '雪山', '草原', '沙漠'])

// 计算属性
const totalPages = computed(() => Math.ceil(pagination.total / pagination.pageSize))

// 跳转到游记详情
const goToPost = (postId: number) => {
  router.push({ name: 'PostDetail', params: { id: postId } })
}

// 跳转到创建游记
const goToCreate = () => {
  ElMessage.info('创建游记功能开发中...')
}

// 搜索处理
const handleSearch = async () => {
  pagination.page = 1
  await loadPosts()
}

// 页码变化处理
const handlePageChange = (page: number) => {
  pagination.page = page
  loadPosts()
  // 滚动到顶部
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

// 文本截断
const truncateText = (text: string, length: number) => {
  if (text.length <= length) return text
  return text.substring(0, length) + '...'
}

// 格式化数字
const formatNumber = (num: number) => {
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + 'w'
  } else if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'k'
  }
  return num.toString()
}

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  
  if (days === 0) {
    return '今天'
  } else if (days === 1) {
    return '昨天'
  } else if (days < 7) {
    return `${days}天前`
  } else {
    return date.toLocaleDateString('zh-CN', {
      month: 'short',
      day: 'numeric'
    })
  }
}
// 加载游记数据
const loadPosts = async () => {
  loading.value = true
  try {
    let response
    
    if (filters.keyword || filters.location || filters.tag) {
      // 搜索请求
      response = await searchPosts({
        keyword: filters.keyword,
        location: filters.location,
        tag: filters.tag,
        page: pagination.page,
        pageSize: pagination.pageSize,
        sortBy: filters.sortBy,
        sortOrder: 'desc'
      })
    } else {
      // 普通列表请求
      response = await getNotes()
      console.log('API响应数据结构:', response.data)
    }
    
    if (response) {
        posts.value = response.data
        console.log(posts.value)
    } 
  } catch (error) {
    console.error('加载游记失败:', error)
    ElMessage.error('加载游记失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 监听路由查询参数变化
watch(
  () => route.query,
  (newQuery) => {
    if (newQuery.keyword) {
      filters.keyword = newQuery.keyword as string
    }
    if (newQuery.location) {
      filters.location = newQuery.location as string
    }
    if (newQuery.tag) {
      filters.tag = newQuery.tag as string
    }
    loadPosts()
  },
  { immediate: true }
)

onMounted(() => {
  loadPosts()
})
</script>

<style scoped>
.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 60px 0;
}

.page-title {
  font-size: 3rem;
  font-weight: 700;
  margin-bottom: 10px;
}

.page-subtitle {
  font-size: 1.2rem;
  opacity: 0.9;
  margin: 0;
}

.filter-section {
  padding: 30px 0;
  background: #f8f9fa;
}

.filter-card {
  background: white;
  border-radius: 15px;
  padding: 30px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
}

.posts-section {
  padding: 40px 0;
}

.loading-container,
.empty-container {
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.post-card {
  background: white;
  border-radius: 15px;
  overflow: hidden;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
  transition: all 0.3s;
  cursor: pointer;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.post-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.15);
}

.post-image {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.post-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.post-card:hover .post-image img {
  transform: scale(1.05);
}

.post-overlay {
  position: absolute;
  top: 10px;
  right: 10px;
}

.post-stats {
  display: flex;
  gap: 10px;
}

.post-stats span {
  background: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 5px 10px;
  border-radius: 15px;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.post-content {
  padding: 20px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.post-tags {
  display: flex;
  gap: 8px;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.post-title {
  font-size: 1.2rem;
  font-weight: 600;
  margin-bottom: 10px;
  color: #333;
  line-height: 1.4;
}

.post-location {
  color: #666;
  font-size: 14px;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.post-location i {
  color: #667eea;
}

.post-excerpt {
  color: #888;
  font-size: 14px;
  line-height: 1.6;
  margin-bottom: 20px;
  flex: 1;
}

.post-meta {
  margin-top: auto;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.author-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.author-details {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.author-name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.post-date {
  font-size: 12px;
  color: #999;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}

@media (max-width: 768px) {
  .page-header {
    padding: 40px 0;
    text-align: center;
  }
  
  .page-title {
    font-size: 2.2rem;
  }
  
  .filter-card {
    padding: 20px;
  }
  
  .posts-section {
    padding: 20px 0;
  }
}
</style>


